<!--新建课程包-->
<template>
  <div class="addClassPackage">
    <div class="search_box">
      <div  class="btn btn_add" @click="showPopup('ruleForm')">
        <i class="el-icon-plus"></i>
        <span class="btn_txt">新建课程包</span>
      </div>
      
    </div>
    
    <div class="table_box">
      <adminTable :tableHead="tableHead" :tableData="tableData"></adminTable>
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.curPage"
        :page-sizes="[10, 20, 50]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.totalRows">
      </el-pagination>
    </div>

    <transition name="el-fade-in-linear">
      <div class="popup-container" v-show="popupState.showStatus">
        <div class="popup">
          <i class="el-icon-error icon_close" @click="popupState.showStatus = false"></i>
          <div class="title">{{popupState.popupName}}</div>

          <div v-if="popupState.popupName == '获取课程码'" class="content">
            <el-form :model="formData" ref="ruleForm" :disabled="popupState.popupName == '教室详情'"  :inline="true"  label-position="left"
               class="form">
              <el-form-item label="生成数量 : "   size="small" class="">
                <el-input  v-model="codeCount" autocomplete="off" ></el-input>
              </el-form-item>
              <div class="btn btn_add" @click="getCode" style="text-align: center;">
                <span class="btn_txt">生成</span>
              </div>
            </el-form>

            <ul class="code_list">
              <li v-for="(item, index) in codeList" :key="index">{{item.subjectPackageCode}}</li>
            </ul>
            
          </div>

          <div v-else class="content">
            <el-form :model="formData" ref="ruleForm" :disabled="popupState.popupName == '教室详情'"  :inline="true"  label-position="left"
               class="form">
              <div style="overflow:hidden">
                
                <el-form-item label="课程包名称 : "   size="small" class="">
                  <el-input  v-model="formData.subjectPackageName" autocomplete="off" ></el-input>
                </el-form-item>
                <div class="class_list">
                  

                  <h4 style="margin-bottom: 10px;">课程包属性</h4>
                  <div class="radio_box" style="margin-bottom: 10px;">
                    <span>课程类型：</span>
                    <el-radio :disabled="popupState.popupName == '编辑'" v-model="formData.packageType" label="1">定期课程</el-radio>
                    <el-radio :disabled="popupState.popupName == '编辑'" v-model="formData.packageType" label="2">非定期课程</el-radio>
                  </div>

                  <el-form-item label="课程周期 : " v-if="formData.packageType == 2"  style="width: 300px;margin-bottom: 10px" size="small" class="">
                    <el-select style="width: 100%;" :disabled="popupState.popupName == '编辑'" multiple v-model="formData.cycleArr">
                      <el-option  label="周一" value="1"></el-option>
                      <el-option  label="周二" value="2"></el-option>
                      <el-option  label="周三" value="3"></el-option>
                      <el-option  label="周四" value="4"></el-option>
                      <el-option  label="周五" value="5"></el-option>
                      <el-option  label="周六" value="6"></el-option>
                      <el-option  label="周日" value="7"></el-option>
                    </el-select>
                  </el-form-item>
                  <div class="clear"></div>
                  <el-form-item label="开课日期 : " style="width: 300px;margin-bottom: 10px" prop="startTime" size="small" class="" v-if="formData.packageType == 2">
                    <!-- <el-date-picker
                      v-model="formData.startTime"
                      type="datetime"
                      value-format="yyyy-MM-dd hh:mm:ss"
                      placeholder="选择日期">
                    </el-date-picker> -->
                    <el-time-picker
                      v-model="formData.startTimeDate"
                      value-format="HH:mm:ss"
                      placeholder="选择时间">
                    </el-time-picker>
                  </el-form-item>
                  
                  <div class="clear"></div>

                  <el-form-item label="每天上课数量 : " v-if="formData.packageType == 2" class="maxHours" style="width: 200px;margin-bottom: 0"  size="small" >
                    <el-input v-model="formData.subjectCount" autocomplete="off" style="width: 100%"></el-input>
                  </el-form-item>
                  <el-form-item label="最大课程数量 : " v-if="formData.packageType == 2" class="maxHours" style="width: 200px;margin-bottom: 0"  size="small" >
                    <el-input :disabled="popupState.popupName == '编辑'" v-model="formData.maxHours" autocomplete="off" style="width: 100%"></el-input>
                  </el-form-item>
                </div>

                



                <div class="clear"></div>

                <h4 style="margin-bottom: 20px;margin-top: 10px;">课程包内容：课程类</h4>

                <ul class="class_list">
                  <li class="class_item" v-for="(item, index) in classList" :key="index">
                    <span class="fl">{{index + 1}}.</span>
                    <el-form :model="item" ref="ruleForm" :inline="true"  label-position="left" class="form">
                      <div style="overflow:hidden">
                        <el-form-item label="课程名称 : " style="width: 250px;" prop="subjectId" size="small" class="">
                          <el-select style="width: 100%;" v-model="item.subjectId">
                            <el-option v-for="(item,key) in classSelectList" :key="key" :label="item.subjectName" :value="item.subjectId">
                            </el-option>
                          </el-select>
                        </el-form-item>

                        <el-form-item label="开课日期 : " v-if="formData.packageType == 1" style="width: 280px;" prop="startTime" size="small" class="">
                          <el-date-picker
                            v-model="item.startTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm"
                            placeholder="选择日期">
                          </el-date-picker>
                        </el-form-item>
                      </div>

                    </el-form>
                    <span class="operation" @click="deleteClass(item, index)">删除</span>
                    <span class="operation" @click="addClass" v-if="index == classList.length - 1">添加</span>
                  </li>
                </ul>

                
                <h4 style="margin-bottom: 20px; margin-top: 10px;">课程包内容：打卡任务类</h4>

                <ul class="class_list">
                  <li class="class_item" v-for="(item, index) in taskList" :key="index">
                    <span class="fl">{{index + 1}}.</span>
                    <el-form :model="item" ref="ruleForm" :inline="true"  label-position="left" class="form">
                      <div style="overflow:hidden">
                        <el-form-item label="任务名称 : " style="width: 250px;" prop="schoolId" size="small" class="">
                          <el-select style="width: 100%;" v-model="item.clockId">
                            <el-option v-for="(item,key) in taskSelectList" :key="key" :label="item.clockName" :value="item.clockId">
                            </el-option>
                          </el-select>
                        </el-form-item>

                        <el-form-item label="起止日期 : "  prop="classRoomName" size="small" class="">
                          <el-date-picker
                            v-model="item.time"
                            type="datetimerange"
                            value-format="yyyy-MM-dd HH:mm"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
                          </el-date-picker>
                        </el-form-item>
                      </div>

                    </el-form>
                    <span class="operation" @click="deleteTask(item, index)">删除</span>
                    <span class="operation" @click="addTask" v-if="index == taskList.length - 1">添加</span>
                  </li>
                </ul>

                <!-- <span class="addClassItem" @click="addClassItem">添加</span> -->
                
              </div>

            </el-form>

            <div class="btn_box">
              <div class="btn btn_add" v-if="popupState.popupName == '新建课程包'" @click="submitAdd('ruleForm')">
                <span class="btn_txt">保存</span>
              </div>

              <div class="btn btn_add" v-if="popupState.popupName == '编辑'" @click="submitEdit('ruleForm')">
                <span class="btn_txt">保存</span>
              </div>
            </div>

          </div>

          
        </div>
      </div>
    </transition>
  </div>
</template>

<style>
.addClassPackage .class_item .el-form-item {
  margin-bottom: 0 !important;
}
.addClassPackage .popup .school_list .school_item .el-form-item--small.el-form-item  {
  margin-bottom: 0;
  margin: 15px 0;
}
.addClassPackage .popup .school_list .school_item .el-form-item--small.el-form-item label {
  width: 60px !important;
}

.addClassPackage .popup .el-input--small {
  width: 100%;
}
.addClassPackage .popup .el-form-item--mini.el-form-item, 
.addClassPackage .popup .el-form-item--small.el-form-item {
  margin-right: 20px;
  width: 30.5%;
  margin-bottom: 25px;
}
.addClassPackage .popup .el-form-item__content {
  width: calc(100% - 90px)
}

.maxHours .el-form-item__content{
  width: calc(100% - 120px) !important;
}

.addClassPackage .avatar-uploader {
  margin-right: 20px;
}
.addClassPackage .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.addClassPackage .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.addClassPackage .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}
.addClassPackage .avatar {
  width: 80px;
  height: 80px;
  display: block;
}
</style>

<style scoped>

.code_list{
  display: flex;
  flex-wrap: wrap;
}
.code_list li {
  width: 33%;
}

.operation {
  cursor: pointer;
  color: #77A4FF;
} 
.class_list {
  padding-bottom: 15px;
  border-bottom: 1px dashed #ccc;
}
.class_item {
  display: flex;
  /* padding-bottom: 10px; */
  margin-top: 20px;
  align-items: center;
  /* border-bottom: 1px dashed #ccc; */
}
.class_item > div {
  display: flex;
  align-items: center;
}
.class_item span {
  margin-right: 20px;
}
.addClassItem {
  font-size: 20px;
  margin-top: 20px;
  display: inline-block;
  cursor: pointer;
}


.addClassPackage .btn_add i {
  margin-right: 5px;
  margin-left: 10px;
}

.el-icon {
  cursor: pointer;
  color: #77A4FF;
}
.school_list .school_item {
  background: #F0F2F5;
  padding: 0 0 0 20px !important;
  box-sizing: border-box;
  margin-bottom: 10px;;
}



.btn_box {
  margin-top: 20px;
}
.popup .content {
  padding-top: 30px;
}
</style>

<script>
import adminTable from '@/components/assembly/adminTable'
import {
  createNamespacedHelpers
} from "vuex";
let {
  mapState,
  mapGetters,
  mapMutations,
  mapActions
} = createNamespacedHelpers("addClassPackage");
export default {
  name: 'addClassPackage',
  data() {
    return {
      codeCount: '',
      codeList: [],
      classId: '',
      classList: [{
        subjectId: '',
        subjectName: '',
        startTime: '',
      }],
      taskList: [{
        clockId: '',
        clockName: '',
        startTime: '',
        endTime: '',
        time: [],
      }],
      popupState: {
        showStatus: false,
        popupName: '新建课程包',
      },
      page: {
        curPage: 1,
        pageSize: 10,
        totalRows: 0,
      },
      formData: {
        subjectPackageName: '',
        packageType: '1',
        cycleArr: [],
        subjectCount: '',
        maxHours: '',
        startTimeDate: '',
      },

      tableHead: {
        // border: true,
        // operation_width: '150px',
        setFunction: [
          {
            showState: "0",
            hideKey: "showUpdate",
            fun: this.tableShowCode,
            name: "获取课程码"
          },
          {
            showState: "0",
            hideKey: "showUpdate",
            fun: this.tableEdit,
            name: "编辑"
          },
          {
            showState: "0",
            hideKey: "showDelete",
            fun: this.tableDelete,
            name: "删除"
          },
        ],
        data: [
          {
            name: '课程包名称',
            key: 'subjectPackageName',
            align: 'center',
          },
          // {
          //   name: "课程包编号",
          //   key: "schoolName",
          //   align: "center",
          // },
        ]
      },
      tableData: [],

      classSelectList: [],
      taskSelectList: [],

      subjectRemoveIdList: [],
      clockRemoveIdList: [],

      subjectPackageId: '',

    }
  },
  created() {
    this.jwtAuth = JSON.parse(sessionStorage.getItem('jwtAuth'));
    
    this.initSelect();
    this.initData();
  },
  
  
  methods: {
    ...mapMutations([
      "updateInfo",
    ]),
    ...mapActions([
      "formGet",
      "post"
    ]),
    addClassItem() {
      let obj = {
        hasInteractive: false,
        imageUrl: '',
        answerImgA: '',
        answerImgB: '',
        voiceName: '',
        answerVoice: '',
      }

      this.classList.push(obj)
    },

    deleteClassItem(index) {
      if(this.classList.length == 1) {
        return false
      }
      this.classList.splice(index, 1);
    },

    
    showPopup(formName) {
      this.popupState = {
        showStatus: true,
        popupName: '新建课程包',
      };

      this.classList = [{}],
      this.taskList = [{}],
      this.formData = {
        subjectPackageName: '',
        packageType: '1',
        cycleArr: [],
        subjectCount: '',
        maxHours: '',
        startTimeDate: '',
      }

      // this.$refs[formName].resetFields();   // 初始化
      
    },

    initData(searchForm) {
      let data = {}
      data.curPage = this.page.curPage;
      data.pageSize = this.page.pageSize;
      
      

      this.post({
        API: 'selectBmOnlineSubjectPackagePageList',
        data: data
      }).then(res => {
        console.log(res);
        this.tableData = res.data;
        

        this.page = res.page;
      }).catch(err => {
        this.$message.error(err);
      })
    },

    

    // 新增提交
    submitAdd(formName) {
      let data = {}
      Object.assign(data, this.formData)

      

      this.taskList.forEach((item, index) => {
        if(item.time) {
          item.startTime = item.time[0]
          item.endTime = item.time[1]
          item.sort = index;
        }
        this.taskSelectList.forEach(selectItem => {
          if(item.clockId == selectItem.clockId) {
            item.clockName = selectItem.clockName
          }
        })
      })
      if(!this.taskList[0].clockId) {
        this.taskList = [];
      }

      this.classList.forEach((item, index) => {
        item.sort = index;
        this.classSelectList.forEach(selectItem => {
          if(item.subjectId == selectItem.subjectId) {
            item.subjectName = selectItem.subjectName
          }
        })
      })
      // console.log(this.classList)
      // console.log(this.taskList)

      data.bmOnlineSubjectPackageSubjects = this.classList
      data.bmOnlineSubjectPackageClocks = this.taskList
      if(this.formData.packageType == '2') {
        if(this.formData.cycleArr.length == 0) {
          this.$message.error('请选择课程周期')
          console.log('请选择课程周期')
          return false;
        }
        if(!this.formData.startTimeDate) {
          this.$message.error('请选择上课时间');
          console.log('请选择上课时间')
          return false;
        }

        if(!this.formData.subjectCount) {
          this.$message.error('请输入每天上课数量')
          console.log('请输入每天上课数量')
          return false;
        }
        if(!this.formData.maxHours) {
          this.$message.error('请输入最大课程数')
          console.log('请输入最大课程数')
          return false;
        }

        let numberReg = new RegExp(/^[0-9]*$/);
        if(!numberReg.test(this.formData.subjectCount)) {
          this.$message.error('每天上课数必须为数字')
          console.log('每天上课数必须为数字')
          return false;
        }
        if(!numberReg.test(this.formData.maxHours)) {
          this.$message.error('最大课程数必须为数字')
          console.log('最大课程数必须为数字')
          return false;
        }

        if(this.classList.length > this.formData.maxHours) {
          this.$message.error('课程数量已超过设置的最大课程数量');
          console.log('课程数量已超过设置的最大课程数量')
          return false;
        }

        data.cycle = data.cycleArr.join(',')
        data.startTime = '1991-01-01 ' + data.startTimeDate
      }else{
        data.startTime = ''
      }

      
      console.log(data);
      // return false;

      this.post({
        API: 'insert',
        data: data
      }).then(res => {
        this.$message.success('新建成功')
        this.popupState.showStatus = false;
        this.initData();
      }).catch(err => {
        this.$message.error(err);
      })
      
    },
    // 获取课程码
    getCode() {
      let data = {
        subjectPackageId: this.subjectPackageId,
        codeCount: this.codeCount
      }
      this.formGet({
        API: 'getCanUseCode',
        data: data
      }).then(res => {
        // console.log(res);
        this.codeList = res;
      }).catch(err => {
        this.$message.error(err);
      })
    },
    
    tableShowCode(rowData) {
      // this.popupState.popupName = '获取课程码'
      this.subjectPackageId = rowData.row.subjectPackageId;
      this.popupState = {
        showStatus: true,
        popupName: '获取课程码',
      }
      this.codeList = [];
      
    },
    // 表格编辑 回显
    tableEdit(rowData) {
      this.subjectRemoveIdList = []
      this.clockRemoveIdList = []
      console.log(rowData.row)
      this.subjectPackageId = rowData.row.subjectPackageId;
      let data = {
        id: this.subjectPackageId,
      }
      this.formGet({
        API: 'selectById',
        data: data
      }).then(res => {
        console.log(res);
        this.popupState = {
          popupName: '编辑',
          showStatus: true,
        }
        this.formData = res;
        if(!this.formData.packageType) {
          this.$set(this.formData, 'packageType', '1')
        }

        if(this.formData.cycle) {
          this.formData.cycleArr = this.formData.cycle.split(',')
        }
        if(this.formData.startTime) {
          this.$set(this.formData, 'startTimeDate', this.formData.startTime.split(' ')[1])
        }

        console.log(this.formData.startTimeDate)

        this.classList = res.bmOnlineSubjectPackageSubjects
        if(res.bmOnlineSubjectPackageClocks) {
          res.bmOnlineSubjectPackageClocks.forEach(item => {
            let time = [];
            time.push(item.startTime)
            time.push(item.endTime)
            this.$set(item, 'time', time)
          })
          this.taskList = res.bmOnlineSubjectPackageClocks
        }

        if(!res.bmOnlineSubjectPackageClocks) {
          this.taskList = [{}];
        }
        
      }).catch(err => {
        this.$message.error(err);
      })
    },

    // 编辑提交
    submitEdit(rowData) {
      let data = {}
      Object.assign(data, this.formData)

      this.taskList.forEach((item, index) => {
        if(item.time) {
          item.startTime = item.time[0]
          item.endTime = item.time[1]
        }
        item.sort = index;
        this.taskSelectList.forEach(selectItem => {
          if(item.clockId == selectItem.clockId) {
            item.clockName = selectItem.clockName
          }
        })
      })

      this.classList.forEach((item, index) => {
        item.sort = index;
        this.classSelectList.forEach(selectItem => {
          if(item.subjectId == selectItem.subjectId) {
            item.subjectName = selectItem.subjectName
          }
        })
      })

      data.bmOnlineSubjectPackageSubjects = this.classList
      data.bmOnlineSubjectPackageClocks = this.taskList

      data.subjectRemoveIdList = this.subjectRemoveIdList
      data.clockRemoveIdList   = this.clockRemoveIdList
      

      console.log(data);
      // return false;
      if(this.formData.packageType == '2') {
        if(this.formData.cycleArr.length == 0) {
          this.$message.error('请选择课程周期')
          console.log('请选择课程周期')
          return false;
        }
        if(!this.formData.startTimeDate) {
          this.$message.error('请选择上课时间');
          console.log('请选择上课时间')
          return false;
        }

        if(!this.formData.subjectCount) {
          this.$message.error('请输入每天上课数量')
          console.log('请输入每天上课数量')
          return false;
        }
        if(!this.formData.maxHours) {
          this.$message.error('请输入最大课程数')
          console.log('请输入最大课程数')
          return false;
        }

        let numberReg = new RegExp(/^[0-9]*$/);
        if(!numberReg.test(this.formData.subjectCount)) {
          this.$message.error('每天上课数必须为数字')
          console.log('每天上课数必须为数字')
          return false;
        }
        if(!numberReg.test(this.formData.maxHours)) {
          this.$message.error('最大课程数必须为数字')
          console.log('最大课程数必须为数字')
          return false;
        }

        if(this.classList.length > this.formData.maxHours) {
          this.$message.error('课程数量已超过设置的最大课程数量');
          console.log('课程数量已超过设置的最大课程数量')
          return false;
        }
        data.startTime = '1991-01-01 ' + data.startTimeDate
      }

      this.post({
        API: 'update',
        data: data
      }).then(res => {
        this.$message.success('修改成功');
        this.initData();
        this.popupState.showStatus = false;
      }).catch(err => {
        this.$message.error(err);
      })
    },
    // 表格删除
    tableDelete(rowData) {
      console.log(rowData)
      let subjectPackageId = rowData.row.subjectPackageId;
      let data = {
        id: subjectPackageId,
      }

      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formGet({
          API: 'deleteById',
          data: data
        }).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.initData();
        }).catch(err => {
          this.$message.error(err);
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },



    deleteClass(item, index){
      console.log(item);
      if(this.classList.length == 1) {
        return false;
      }
      this.subjectRemoveIdList.push(item.subjectPackageSubjectId)
      this.classList.splice(index, 1)
    },
    addClass() {
      let obj = {}
      this.classList.push(obj)
    },
    deleteTask(item, index){
      console.log(item);
      if(this.taskList.length == 1) {
        return false;
      }
      this.clockRemoveIdList.push(item.subjectPackageClockId)
      this.taskList.splice(index, 1)
    },
    addTask() {
      let obj = {}
      this.taskList.push(obj)
    },


    initSelect() {
      this.post({
        API: 'queryAllSubject',
        data: {}
      }).then(res => {
        // console.log(res)
        this.classSelectList = res;
      }).catch(err => {
        this.$message.error(err);
      });

      this.post({
        API: 'queryAllClock',
        data: {}
      }).then(res => {
        console.log(res)
        this.taskSelectList = res;
      }).catch(err => {
        this.$message.error(err);
      });
    },
    
    

    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.page.pageSize = val;
      this.initData();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page.curPage = val;
      this.initData();
    }
    
  },
  computed: {
    ...mapState([
    ]),
    // ...mapGetters(["selectedIds"])
  },
  components: {
    adminTable,
  },
}

</script>